package com.fujitsu.cn.fnst.controller;

import java.awt.image.BufferedImage;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fujitsu.cn.fnst.base.BaseController;
import com.fujitsu.cn.fnst.common.StringUtils;
import com.fujitsu.cn.fnst.entiy.Meeting;
import com.fujitsu.cn.fnst.entiy.User;
import com.fujitsu.cn.fnst.service.MeetingBookService;
import com.fujitsu.cn.fnst.service.MeetingService;
import com.fujitsu.cn.fnst.service.UserService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class IndexController extends BaseController {
    @Resource
    private Producer captchaProducer;
    @Resource
    private UserService usersService;
    @Resource
    private MeetingBookService meetingBookService;
    @Resource
    private MeetingService meetingsService;

    private static final int MAXAGE = 60 * 60 * 24 * 30;

    @RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
    public String login(Model model, HttpSession session) {
        if (!isLogin(session)) {
            model.addAttribute("error", "-1");
            return "login/login";
        }
        return redirect("/index");
    }

    @RequestMapping(value = { "/login" }, method = RequestMethod.POST)
    public String login(String user, String pwd, String checkCode,
            HttpSession session, Model model) {
        if (user == null || user.trim().equals("")) {
            model.addAttribute("error", "请输入用户名!");
            return "login/login";
        }
        if (pwd == null || pwd.trim().equals("")) {
            model.addAttribute("error", "请输入密码!");
            return "login/login";
        }
        if (checkCode == null || checkCode.trim().equals("")) {
            model.addAttribute("error", "请输入验证码!");
            return "login/login";
        }
        String code = (String) session
                .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (!code.equals(checkCode)) {
            model.addAttribute("error", "验证码不正确!");
            return "login/login";
        }

        User user1 = usersService.findUser(user);
        if (user1 == null) {
            model.addAttribute("error", "请输入正确的用户名!");
            return "login/login";
        }
        if (!user1.getPassword().equals(StringUtils.encrypt(pwd))) {
            model.addAttribute("error", "请输入正确的密码!");
            return "login/login";
        }
        session.setAttribute(LOGIN, "true");
        session.setAttribute("user", user1);
        return redirect("/index");
    }

    @RequestMapping(value = { "/index" })
    public String index(Model model, HttpSession session,
            HttpServletRequest request, HttpServletResponse response) {
        if (!isLogin(session)) {
            return redirect("/login");
        }
        String cookieValue = getCookieValue(request, PREFERENCE, true);
        if (cookieValue == null) {
            session.setAttribute(PREFERENCE, "time");
        } else {
            session.setAttribute(PREFERENCE, cookieValue);
        }
        return "index/index";
    }

    @RequestMapping(value = { "/logout" })
    public String logout(Model model, HttpSession session) {
        setLogOutStatus(session);
        return redirect("/login");
    }

    /**
     * 产生验证码的方法
     * */
    @RequestMapping(value = "/captcha-image", method = RequestMethod.GET)
    public void createCaptcha(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
                capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    @RequestMapping("/meeting")
    public String setMeetingMode(Model model, HttpSession session,
            HttpServletRequest request, HttpServletResponse response) {
        if (!isLogin(session)) {
            return redirect("/login");
        }
        setCookie(request, response, PREFERENCE, "meeting", MAXAGE, true);
        session.setAttribute(PREFERENCE, "meeting");
        return "/index/index";
    }

    @RequestMapping("/function")
    public String setFuctionMode(Model model, HttpSession session,
            HttpServletRequest request, HttpServletResponse response) {
        if (!isLogin(session)) {
            return redirect("/login");
        }
        setCookie(request, response, PREFERENCE, "function", MAXAGE, true);
        session.setAttribute(PREFERENCE, "function");
        return "/index/index";
    }

    @RequestMapping("/time")
    public String setTimeMode(Model model, HttpSession session,
            HttpServletRequest request, HttpServletResponse response) {
        if (!isLogin(session)) {
            return redirect("/login");
        }
        setCookie(request, response, PREFERENCE, "time", MAXAGE, true);
        session.setAttribute(PREFERENCE, "time");
        return "/index/index";
    }

    @RequestMapping("/other")
    public String setOtherMode(Model model, HttpSession session,
            HttpServletRequest request, HttpServletResponse response) {
        if (!isLogin(session)) {
            return redirect("/login");
        }
        setCookie(request, response, PREFERENCE, "other", MAXAGE, true);
        session.setAttribute(PREFERENCE, "other");
        return "/index/index";
    }

    @RequestMapping("/status")
    public String status(Model model) {
        // List<MeetingModel> aMeetings = meetingBookService.getMeetingState(
        // "building='A'", "floor asc,number asc");
        // List<MeetingModel> bMeetings = meetingBookService.getMeetingState(
        // "building='B'", "floor asc,number asc");
        // model.addAttribute("meeting_rooms_a", aMeetings);
        // model.addAttribute("meeting_rooms_b", bMeetings);
        return "/status/status";
    }

    @ResponseBody
    @RequestMapping(value = "/meetings/all", method = RequestMethod.GET)
    public Object meetings(Model model) {
        List<Meeting> aMeetings = meetingsService.findByWhereAndOrder(
                "building='A'", "floor asc,number asc");
        List<Meeting> bMeetings = meetingsService.findByWhereAndOrder(
                "building='B'", "floor asc,number asc");
        model.addAttribute("meeting_rooms_a", aMeetings);
        model.addAttribute("meeting_rooms_b", bMeetings);
        return new Object[] { aMeetings, bMeetings };
    }

    /**
     * ajax设置其选择模式
     * */
    @RequestMapping(value = "/selectMode", method = RequestMethod.GET)
    @ResponseBody
    public boolean selectMode(Model model, String mode,
            HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        if (!isLogin(session)) {
            return false;
        }
        setCookie(request, response, PREFERENCE, mode, MAXAGE, true);
        session.setAttribute(PREFERENCE, mode);
        return true;
    }

    /**
     * ajax校验验证码是否正确
     * */
    @RequestMapping(value = "/checkVerifyCode", method = RequestMethod.GET)
    @ResponseBody
    public boolean checkVerifyCode(Model model, String verifycode,
            HttpSession session) {
        String code = (String) session
                .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (!code.equals(verifycode)) {
            return false;
        } else {
            return true;
        }
    }
}
